function throttle(callback, wait, options) {
  let timeout, that, args, result;
  let previous = 0;
  if (!options) options = {};
  const later = function () {
    callback.apply(that, args)
    previous = Date.now();
    clearTimeout(timeout);
    timeout = null;
  }

  const throttled = function () {
    that = this;
    args = arguments;
    let now = Date.now();
    if (options.leading === false && !previous) previous = now;
    if (now - previous > wait) {
      if (timeout) {
        clearTimeout(timeout)
        timeout = null;
      }
      result = callback.apply(that, args)
      previous = now;
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, wait)
    }
    return result;
  }
  throttled.cancel = function () {
    clearTimeout(timeout);
    timeout = that = args = null;
  }
  return throttled
}
